"""


"""
from django.contrib.auth.backends import ModelBackend
import re

from users.models import User


class MyAuthenticatewithBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):

        # # 判断传过来的username是否是手机号
        # if re.match('1[3-9]\d{9}', username):
        #     # 判断密码是否正确
        #     user = User.objects.get(mobile=username)
        #
        # else:
        #     user = User.objects.get(username=username)
        #
        # return user

        if not request:
            try:
                if re.match('^1[3-9]\d{9}$', username):
                    # 手机号登录
                    user = User.objects.get(mobile=username)
                else:
                    # 用户名登录
                    user = User.objects.get(username=username)
            except User.DoesNotExist:
                return None
            else:
                if not user.is_superuser:
                    return None

                if user and user.check_password(password):
                    return user
                else:
                    return None

        else:
            try:
                if re.match('^1[3-9]\d{9}$', username):
                    # 手机号登录
                    user = User.objects.get(mobile=username)
                else:
                    # 用户名登录
                    user = User.objects.get(username=username)
            except User.DoesNotExist:
                return None
            else:
                if user and user.check_password(password):
                    return user
                else:
                    return None



